package com.imooc.security.core.social.qq.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;

public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {
    private final String URL_GET_USER_INFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";
    private final String URL_GET_OPEN_ID = "https://graph.qq.com/oauth2.0/me?access_token=%s";

    private String appId;
    private String openId;

    private ObjectMapper objectMapper=new ObjectMapper();

    @Override
    public QQUserInfo getQqUserInfo() {
        String url =String.format(URL_GET_USER_INFO,appId,openId);
        String forObject = getRestTemplate().getForObject(url, String.class);
        System.out.println(forObject);
        QQUserInfo qqUserInfo=null;
        try {
            qqUserInfo = objectMapper.readValue(forObject, QQUserInfo.class);
            qqUserInfo.setOpenId(openId);
            return qqUserInfo;
        } catch (IOException e) {
            throw new RuntimeException("获取用户信息失败",e);
        }
    }

    public QQImpl(String accessToken, String appId) {
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
        this.appId = appId;
        String url = String.format(URL_GET_OPEN_ID,accessToken);
        String result = getRestTemplate().getForObject(url,String.class);
        System.out.println(result);

        this.openId=StringUtils.substringBetween("\"openid\":\"","\"}");
    }

}
